package com.example.treasure_back.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.treasure_back.entity.BusinessException;
import com.example.treasure_back.entity.MsgEntity;
import com.example.treasure_back.mapper.UserMapper;
import com.example.treasure_back.model.UserModel;
import com.example.treasure_back.model.vo.ImageUploadResult;
import com.example.treasure_back.service.UserService;
import com.example.treasure_back.shiroEntity.auth.AuthUser;
import com.example.treasure_back.utils.AliOSSUtils;
import com.example.treasure_back.utils.JwtUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Objects;

@RestController
@RequestMapping("/treasure/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    private final static String[] allowFileType = new String[]{".bmp", ".jpg", ".jpeg", ".png", ".gif"};

    @RequestMapping("/login")
    public MsgEntity login(@RequestBody JSONObject jsonObject) {
        String email = jsonObject.getString("email");
        String password = jsonObject.getString("password");
        UserModel userModel = userMapper.selectById(email);
        if (userModel == null || !userModel.getPassword().equals(password)) {
            throw new BusinessException("-1","用户名或密码错误");
        }
        //创建chaim填入用户信息数据
        HashMap<String, Object> chaim = new HashMap<>();
        chaim.put("email", email);
        //过期时间为一天
        return new MsgEntity("SUCCESS", "200", jwtUtils.encode(email, 3 * 24 * 60 * 60 * 1000, chaim));
    }

    @PostMapping("/register")
    public MsgEntity register(@RequestBody JSONObject jsonObject){
        String email = jsonObject.getString("email");
        String password = jsonObject.getString("password");
        String username = jsonObject.getString("username");
        Boolean register = userService.register(email, password, username);
        if (register){
            return new MsgEntity("SUCESS","200","注册成功");
        }
        else{
            throw new BusinessException("-1","注册失败");
        }

    }

    @RequestMapping("/getUserInfoByEmail")
    public MsgEntity getUserInfoByEmail(@AuthUser String email) throws IncorrectCredentialsException {
        UserModel user = userMapper.selectById(email);
        user.setPassword(null);
        return new MsgEntity("SUCCESS", "200",user);
    }

    @RequestMapping("/forgetPassword/{email}")
    public MsgEntity forgetPassword(@PathVariable String email){
        String code = userService.sendEmail(email);
        if(code != null){
            return new MsgEntity("SUCCESS","200",code);
        }
        else{
            throw new BusinessException("-1","用户未注册");
        }
    }

    @RequestMapping("/sendRegEmail/{email}")
    public MsgEntity sendRegEmail(@PathVariable String email) throws MessagingException, IOException {
        String code = userService.sendRegEmail(email);
        if(code.equals("-1")){
            throw new BusinessException("-1","用户已注册");
        }
        else {
            return new MsgEntity("SUCCESS","200",code);
        }
    }

    @PostMapping("/resetPassword")
    public MsgEntity resetPassword(@RequestBody JSONObject jsonObject){
        String email = jsonObject.getString("email");
        String password = jsonObject.getString("password");
        System.out.println(email);
        System.out.println(password);
        boolean b = userService.resetPassword(email, password);
        if(b){
            return new MsgEntity("SUCCESS","200","重置成功");
        }
        else {
            throw new BusinessException("-1","重置失败");
        }
    }

    @PostMapping("/uploadAvatar")
    public MsgEntity uploadAvatar(@AuthUser String email, @RequestParam("file") MultipartFile file) throws IOException {

        if (file.isEmpty()){
            throw new BusinessException("-1", "上传图片为空");
        }
        else {
            if(!Objects.requireNonNull(file.getOriginalFilename()).contains(".")){
                throw new BusinessException("-1", "文件名解析异常");
            }
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            if (suffix.isEmpty() || !Arrays.asList(allowFileType).contains(suffix.toLowerCase())){
                throw new BusinessException("-1", "文件格式出错");
            }
            // 上传到oss
            ImageUploadResult imageUploadResult = userService.uploadAvatar(email, file.getInputStream(), suffix);
            return new MsgEntity("SUCCESS","200", imageUploadResult);

        }
    }

    @PostMapping("/resetUsername")
    public MsgEntity resetUsername(@AuthUser String email,@RequestBody JSONObject jsonObject){
        String username = jsonObject.getString("username");
        if (username == null){
            throw new BusinessException("-2","未提交用户名");
        }
        userService.resetUsername(email,username);
        return new MsgEntity("SUCCESS", "200", "重置成功");
    }

}
